// tracker.js 完整改造版
export class Tracker {
	constructor() {
		this.queue = []
		this.isSending = false
		this.sendTimer = null
	}

	// 通用埋点方法
	track(eventType, data = {}) {
		const systemInfo = uni.getSystemInfoSync()
		const currentPage = getCurrentPages().pop()
		const now = Date.now()
		const event = {
			eventType,
			appName: systemInfo.appName,
			appId: systemInfo.appId,
			timestamp: now,
			formattedTime: this._formatTime(now), // 新增格式化字段
			platform: systemInfo.platform,
			osVersion: systemInfo.osVersion,
			appVersion: systemInfo.appVersion,
			route: currentPage?.route || '',
			systemInfo: systemInfo,
			...data
		}

		this.queue.push(event)
		console.log('埋点上报数据：', event)
		this._saveToStorage()
		this._scheduleSend()
	}

	// 新增私有格式化方法
	_formatTime(timestamp) {
		const date = new Date(timestamp)
		return {
			iso: date.toISOString(),
			local: `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`,
			timestamp: date.getTime()
		}
	}

	// 错误埋点
	trackError(error, context = {}) {
		this.track('ERROR', {
			error: {
				config: error.config,
				errMsg: error.errMsg,
				message: error.message,
				stack: error.stack,
				...context
			}
		})
	}

	// 用户行为埋点（通过节点ref）
	/*
		@example 
		<!-- 在模板中使用 -->
		<button class="track-btn" @click="trackEvent">按钮</button>
		// 在组件中调用
		this.$tracker.trackElementAction('track-btn', 'click')
	*/
	trackElementAction(ref, eventType) {
		console.log('trackElementAction', ref, eventType)
		uni.createSelectorQuery()
			.select(`.${ref}`)
			.boundingClientRect(res => {
				if (res) {
					this.track('USER_ACTION', {
						element: {
							id: res.id,
							class: res.class,
							dataset: res.dataset,
							text: res.text?.slice(0, 50)
						},
						actionType: eventType
					})
				}
			})
			.exec()
	}

	// 延迟发送合并请求,增加重试间隔参数
	_scheduleSend(delay = 3000) {
		if (this.sendTimer) clearTimeout(this.sendTimer)
		this.sendTimer = setTimeout(() => this._sendData(), delay)
	}

	async _sendData() {
		// 方式1：使用uniCloud接收数据
		if (this.isSending || this.queue.length === 0) return

		this.isSending = true
		const sendData = [...this.queue]

		try {
			const res = await uniCloud.callFunction({
				name: 'track', // 云函数名称
				data: {
					action: 'batchReport',
					events: sendData
				}
			})

			if (res.result.code === 0) {
				this.queue = []
				uni.removeStorageSync('trackerQueue')
			} else {
				throw new Error(res.result.message)
			}
		} catch (e) {
			console.error('埋点上报失败:', e)
			this.queue.unshift(...sendData)
			// 失败重试机制
			if (!this.sendTimer) {
				this._scheduleSend(5000) // 5秒后重试
			}
		} finally {
			this.isSending = false
		}
		
		// 方式2：使用api方式接收数据
		// 	try {
		// 		await new Promise((resolve, reject) => {
		// 			uni.request({
		// 				url: 'https://your-api-domain.com/track',
		// 				method: 'POST',
		// 				header: {
		// 					'Content-Type': 'application/json'
		// 				},
		// 				data: sendData,
		// 				success: (res) => {
		// 					if (res.statusCode === 200) {
		// 						this.queue = []
		// 						uni.removeStorageSync('trackerQueue')
		// 						resolve()
		// 					} else {
		// 						reject(new Error(`上报失败: ${res.statusCode}`))
		// 					}
		// 				},
		// 				fail: reject
		// 			})
		// 		})
		// 	} catch (e) {
		// 		console.error('埋点上报失败:', e)
		// 		this.queue.unshift(...sendData) // 失败数据重新入队
		// 	} finally {
		// 		this.isSending = false
		// 	}
	}
	_saveToStorage() {
		uni.setStorageSync('trackerQueue', JSON.stringify(this.queue))
	}

	init() {
		const history = uni.getStorageSync('trackerQueue')
		if (history) this.queue = JSON.parse(history)
		this._scheduleSend() // 初始化时启动定时发送
	}
}

// 补零函数
function pad(n) {
	return n.toString().padStart(2, '0')
}